<template>
  <div class="chart-wrapper">
    <chart
      :option="refChartOption"
      :style="{ height: `${chartHeight}` }"
      v-bind="$attrs"
      @zrender:click="pieRenderClickHandle"
    />
    <div class="title">
      <span>{{ currentTitle }}</span>
      <span>{{ currentTotal }}</span>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, PropType, ref, watch, watchEffect } from 'vue';
import { Chart, SeriesDataItem } from '@/components';
import { EChartOption } from 'echarts';
import { getActiveOption } from '../options/active-option';
import { labelLineData } from '../../util';
const colors = [
  '#EB5B5B',
  '#E48648',
  '#E8F252',
  '#8BDB22',
  '#23BB23',
  '#22DBC8',
  '#54C0EE',
  '#3555F7',
  '#7975F1',
  '#A15FE3',
  '#A525E3',
  '#D820D2',
  '#E63298',
];

const colorTransparent = [
  'rgba(235, 91, 91, 40%)',
  'rgba(228, 134, 72, 40%)',
  'rgba(232, 242, 82, 40%)',
  'rgba(139, 219, 34, 40%)',
  'rgba(35, 187, 35, 40%)',
  'rgba(34, 219, 200, 40%)',
  'rgba(84, 192, 238, 40%)',
  'rgba(53, 85, 247, 40%)',
  'rgba(121, 117, 241, 40%)',
  'rgba(161, 95, 227, 40%)',
  'rgba(165, 37, 227, 40%)',
  'rgba(216, 32, 210, 40%)',
  'rgba(230, 50, 152, 40%)',
];
export default defineComponent({
  props: {
    data: {
      type: Array as PropType<SeriesDataItem[]>,
      default: () => [],
    },
    height: {
      type: Number,
      default: 200,
    },
    fieldNames: {
      type: Object,
      default: () => ({
        name: 'name',
        value: 'value',
      }),
    },
    title: {
      type: String,
      default: '-',
    },
  },
  emits: ['zrender:click'],
  setup(props, { emit }) {
    const currentTitle = ref<string>(props.title);
    const currentTotal = ref<number>(0);
    const option = getActiveOption();

    const refChartOption = ref(option);

    const chartHeight = computed(() => `${props.height}px`);
    // 总数
    const total = computed(() =>
      props.data.reduce((total, currentValue) => {
        return total + currentValue[props.fieldNames.value];
      }, 0),
    );

    const setChartOption = (data: any[]) => {
      const seriesData: EChartOption.SeriesPie.DataObject[] = [];
      let itemIndex = 0;
      data.forEach(item => {
        if (itemIndex === 13) {
          itemIndex = 0;
        }
        const name = item[props.fieldNames.name];
        const value = item[props.fieldNames.value];
        let itemStyle: any = {};
        itemStyle = {
          normal: { borderColor: colors[itemIndex], color: colorTransparent[itemIndex] },
          emphasis: { color: colors[itemIndex] },
        };
        const seriesItem = {
          name,
          value,
          itemStyle,
        };
        Object.keys(item).forEach(
          o =>
            ![props.fieldNames.name, props.fieldNames.value].includes(o) &&
            (seriesItem[o] = item[o]),
        );

        seriesData.push(seriesItem);
        itemIndex++;
      });

      refChartOption.value.series[0].data = labelLineData(seriesData, 5);
    };

    const pieRenderClickHandle = e => {
      const { dataIndex, status } = setSelectState(e.target);
      setTitle(dataIndex, status);
      emit('zrender:click', e, status);
    };

    // 设置选中状态
    const setSelectState = target => {
      const { data = [] } = refChartOption.value.series[0];
      const dataIndex = target ? target.dataIndex : -1;
      const status = data[dataIndex]
        ? !(data[dataIndex] as EChartOption.SeriesPie.DataObject).selected
        : false;
      if (target) {
        data.forEach((e, i) => (e.selected = target.dataIndex === i ? !e.selected : false));
      } else {
        data.forEach(e => (e.selected = false));
      }
      return {
        status,
        dataIndex,
      };
    };

    // 设置标题
    const setTitle = (dataIndex, status) => {
      if (dataIndex === -1 || !status) {
        currentTitle.value = props.title;
        currentTotal.value = total.value;
      } else {
        currentTitle.value = props.data[dataIndex][props.fieldNames.name];
        currentTotal.value = props.data[dataIndex][props.fieldNames.value];
      }
    };
    watch(
      () => props.data,
      () => {
        currentTitle.value = props.title;
        currentTotal.value = total.value;
        setChartOption(props.data);
      },
    );

    onMounted(() => {
      currentTitle.value = props.title;
      currentTotal.value = total.value;
      setChartOption(props.data);
    });
    return {
      currentTitle,
      currentTotal,
      chartHeight,
      refChartOption,
      setChartOption,
      pieRenderClickHandle,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style lang="less" scoped>
.chart-wrapper {
  position: relative;
  .title {
    position: absolute;
    top: 50%;
    left: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #666;
    font-size: 18px;
    transform: translate(-50%, -50%);
  }
}
</style>
